﻿Imports System.Data.SqlClient
Imports System.IO
Imports System.IO.Compression

Partial Class imggen
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("Management_Info_SysConnectionString").ConnectionString)
            Dim SQL As String = "SELECT [img_id], [img], [img_desc],img_table FROM [img_items] WHERE [img_table] = @PictureID"
            Dim myCommand As New SqlCommand(SQL, myConnection)
            myCommand.Parameters.AddWithValue("@PictureID", Context.Request.QueryString("PictureID"))

            myConnection.Open()
            Dim myReader As SqlDataReader = myCommand.ExecuteReader
            Dim decompressfile As Boolean = True

            If myReader.HasRows = False Then
                myConnection.Close()
                SQL = "SELECT [img_id], [img], [img_desc],img_table FROM [img_items] WHERE [img_table] = @PictureID"
                Dim myExCommand As New SqlCommand(SQL, myConnection)
                myExCommand.Parameters.AddWithValue("@PictureID", "Default")
                myConnection.Open()
                myReader = myExCommand.ExecuteReader
                decompressfile = False
            End If

            If myReader.Read Then
                Context.Response.ContentType = myReader("img_desc").ToString()

                If decompressfile = True Then
                    Context.Response.BinaryWrite(Decompress(myReader("img")))
                Else
                    Context.Response.BinaryWrite(myReader("img"))
                End If
            End If

            myReader.Close()
            myConnection.Close()

        End Using
    End Sub
    Public Shared Function Decompress(bytes As Byte()) As Byte()
        Dim stream = New MemoryStream()
        Dim zipStream = New DeflateStream(New MemoryStream(bytes), CompressionMode.Decompress, True)
        Dim buffer = New Byte(4095) {}
        While True
            Dim size = zipStream.Read(buffer, 0, buffer.Length)
            If size > 0 Then
                stream.Write(buffer, 0, size)
            Else
                Exit While
            End If
        End While
        zipStream.Close()
        Return stream.ToArray()
    End Function
End Class
